'use strict';
const db = uniCloud.database();
const userCollection = db.collection('user');

exports.main = async (event, context) => {
  const { username, password } = event;

  // 参数校验
  if (!username || !password) {
    return {
      code: 400,
      msg: '用户名和密码不能为空'
    }
  }

  try {
    // 检查用户名是否已存在
    const existUser = await userCollection.where({
      username: username
    }).get();

    if (existUser.data && existUser.data.length > 0) {
      return {
        code: 400,
        msg: '用户名已存在'
      }
    }

    // 创建新用户
    const userData = {
      username,
      password, // 实际应用中应该加密存储
      createTime: Date.now(),
      lastLoginTime: Date.now(),
      status: 1 // 1: 正常, 0: 禁用
    };

    const result = await userCollection.add(userData);

    if (result.id) {
      return {
        code: 200,
        msg: '注册成功',
        data: {
          username,
          createTime: userData.createTime
        }
      }
    } else {
      return {
        code: 500,
        msg: '注册失败'
      }
    }

  } catch (error) {
    return {
      code: 500,
      msg: '服务器错误',
      error: error.message
    }
  }
}; 